<?php
class Dig_Tree
{
    protected $_xmlObject;
    /**
     * You can either pass a xml object or a path to a site tree file (XML)
     * You can optionaly pass a domain. if you don't then it will use the current domain.
     *
     * @param mixed $xml Zend_Config object or path to xml file
     * @param string $domain the domain to load
     * 
     */
    public function __construct ($xml, $domain = null)
    {
        if ($xml instanceof SimpleXMLElement) {
            $this->_xmlObject = $xml;
        } else {
            if (null == $domain) {
                $domain = $_SERVER['SERVER_NAME'];
            }
            $this->loadXml($xml, $domain);
        }
    }
    public function getNodeByUri ($uri)
    {
        if (empty($uri) || $uri == '/') {
            return $this->_xmlObject;
        }
        $uriParts = explode('/', $uri);
        if (count($uriParts) > 0) {
            $xpathQuery = '/';
            foreach ($uriParts as $part) {
                if (! empty($part)) {
                    $xpathQuery .= $this->xpathQuery('page', 'id', $part, false);
                }
            }
            return $this->xpath($xpathQuery);
        }
        return false;
    }
    public function getDefaultPage ()
    {
        $xpath = $this->xpathQuery('page', 'default', 'true', true);
        return $this->xpath($xpath);
    }
    public function getNodeById ($id)
    {
        return $this->xpath($this->xpathQuery('page', 'id', $id, true));
    }
    /**
     * This method loads the tree
     *
     * @param mixed $pathToTree This is a description
     * @param string $domain the domain to load
     *
     */
    public function loadXml ($pathToTree, $domain = null)
    {
        $domainPath = str_replace('?', $domain, $pathToTree);
        $defaultPath = str_replace('?', 'default', $pathToTree);
        if (file_exists($domainPath)) {
            $xml = simplexml_load_file($domainPath);
        } else {
            $xml = simplexml_load_file($defaultPath);
        }
        $this->_xmlObject = $xml;
    }
    public function xpath ($pattern)
    {
        return $this->_xmlObject->xpath($pattern);
    }
    static function xpathQuery ($object, $key, $value, $global = false)
    {
        if ($global == false) {
            $pattern = '/';
        } else {
            $pattern = '//';
        }
        $pattern .= sprintf("%s[@%s='%s']", $object, $key, $value);
        return $pattern;
    }
}
?>
